/*
    libnbds
    Non-blocking Data Structures Library

    Copyright (C) 2011 Paweł Dziepak

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef NBDS_LIFO_H
#define NBDS_LIFO_H

#include "type.h"
#include "hazard_pointer.h"

namespace nbds {
	/* The Data Structure Itself (lock-free) */
	class lifo_base {
	private:
		struct elem {
			void *obj;
			elem *next;
		};

		elem *first;

		hazard_pointer<elem*> hp;

	protected:
		lifo_base() : first(0) { }

		void push_(void *);
		void *pop_();

		bool is_empty_() {
			return !first;
		}
	};

	template<typename T, bool is_primitive>
	class lifo_wrapper { };

	template<typename T>
	class lifo_wrapper<T, false> : public lifo_base {
	public:
		void push(const T &x) {
			T *obj = new T(x);
			push_(reinterpret_cast<void*>(obj));
		}

		T pop() {
			T *x = reinterpret_cast<T*>(pop_());

			if (!x)
				return T();

			T obj = *x;
			delete x;

			return obj;
		}

		bool is_empty() {
			return is_empty_();
		}
	};

	template<typename T>
	class lifo_wrapper<T, true> : public lifo_base {
	public:
		void push(const T &x) {
			push_(reinterpret_cast<void*>(x));
		}

		T pop() {
			void *x = pop_();
			T obj = (T)((char*)x - (char*)0);
			return obj;
		}

		bool is_empty() {
			return is_empty_();
		}
	};

	template<typename T>
	class lifo : public lifo_wrapper<T, is_primitive<T>::value> { };
}

#endif
